﻿using System.Linq;
using Daemon.Common;
using Daemon.Common.Helpers;
using Daemon.Infrustructure.EF;
using Daemon.Repository.EF.Enums;
using Daemon.Repository.Contract;
using Daemon.Model;
using System;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Daemon.Repository.EF
{
    public class RoleSecuredItemRepository : Repository<RoleSecuredItem>, IRoleSecuredItemRepository
    {
        protected override Expression<Func<RoleSecuredItem, int>> PrimaryKeyExpression => r => r.Id;

        public RoleSecuredItemRepository(ApiDBContent context) : base(context)
        {
        }

        protected override IEnumerable<RoleSecuredItem> IncludeRelationships(IEnumerable<RoleSecuredItem> entities, ApiDBContent db)
        {
            SetRoleInfo(entities, db);
            SetMenuInfo(entities, db);
            return base.IncludeRelationships(entities, db);
        }
        protected override void UpdateEntitiesBeforeCreate(IEnumerable<RoleSecuredItem> entities, ApiDBContent context)
        {
            var roleIds = entities.Select(r => r.RoleId).ToList();
            var roleSecuredItems = context.RoleSecuredItem.Where(r => roleIds.Contains(r.RoleId));
            context.RoleSecuredItem.RemoveRange(roleSecuredItems);
            base.UpdateEntitiesBeforeCreate(entities, context);
        }

        private void SetRoleInfo(IEnumerable<RoleSecuredItem> entities, ApiDBContent context)
        {
            if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, RoleSecuredItemRelationship.RoleInfo))
            {
                return;
            }

            var roleIds = entities.Select(r => r.RoleId).ToList();
            var roles = context.AdminRole.Where(r => roleIds.Contains(r.Id)).ToDictionary(r => r.Id, r => r.Name);
            foreach (var item in entities)
            {
                if (roles.TryGetValue(item.RoleId, out string roleName))
                {
                    item.RoleName = roleName;
                }
            }
        }

        private void SetMenuInfo(IEnumerable<RoleSecuredItem> entities, ApiDBContent context)
        {
            if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, RoleSecuredItemRelationship.MenuInfo))
            {
                return;
            }

            var menuItemIds = entities.Select(r => r.MenuItemId).ToList();
            var menuItems = context.SystemMenus.Where(r => menuItemIds.Contains(r.Id)).ToDictionary(r => r.Id, r => r);
            foreach (var item in entities)
            {
                if (menuItems.TryGetValue(item.MenuItemId, out SystemMenu menu))
                {
                    item.Menu = menu;
                }
            }
        }
    }
}
